package com.paat.autoconvert;

import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.actionSystem.DocCommandGroupId;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;

/**
 * author: Lipeng.Yu
 * time: 2019/9/18 15:04
 * description:
 */
public class ConvertAction extends AnAction {

    public ConvertAction(){
        super();
    }
    @Override
    public void update(AnActionEvent e) {
        super.update(e);
        boolean visible = isActionAvailable(e);
        final Presentation presentation = e.getPresentation();
        presentation.setVisible(visible);
        presentation.setEnabled(visible);
    }

    private boolean isActionAvailable(AnActionEvent e) {
        final VirtualFile file = getVirtualFiles(e);
        if (getEventProject(e) != null && file != null) {
            final FileType fileType = file.getFileType();
            return StdFileTypes.JAVA.equals(fileType);
        }
        return false;
    }

    private VirtualFile getVirtualFiles(AnActionEvent e) {
        return PlatformDataKeys.VIRTUAL_FILE.getData(e.getDataContext());
    }

    @Override
    public void actionPerformed(AnActionEvent e) {
        Project project = e.getData(PlatformDataKeys.PROJECT);
        final ConvertHandler handler = new ConvertHandler(e.getDataContext(), project);
        boolean processChooser = handler.processChooser();
        if (processChooser) {
            final Editor editor = getEditor(e);
            //Messages.showMessageDialog(project, editor.getDocument().getText(), title, Messages.getInformationIcon());
            CommandProcessor.getInstance().executeCommand(project, new Runnable() {
                @Override
                public void run() {
                    ApplicationManager.getApplication().runWriteAction(handler);
                }
            }, getClass().getName() + "-Commandname", DocCommandGroupId.noneGroupId(editor.getDocument()));
        }
    }

    private Editor getEditor(AnActionEvent e) {
        return PlatformDataKeys.EDITOR.getData(e.getDataContext());
    }
}
